package mips.instructions;

/**
 * <code>ADDU</code> instruction<br/>
 * Add Unsigned<br/>
 * @author jnmartin84@gmail.com
 */
public class ADDU extends Instruction {
	
	private static final ADDU INSTANCE = new ADDU();
	private static final String INSTRUCTION_NAME = "ADDU";

	private ADDU(){}

	public static final ADDU getInstance() {
		return INSTANCE;
	}

	/**
	 * <b>Format:</b><br/>
	 * ADDU rd, rs, rt<br/><br/>
	 * <b>Description:</b><br/>
	 * The contents of general register rs and the contents of general register rt<br/>
	 * are added to form the result. The result is placed into general register rd.<br/>
	 * No overflow exception occurs under any circumstances.<br/>
	 * The only difference between this instruction and the ADD instruction is<br/>
	 * that ADDU never causes an overflow exception.<br/><br/>
	 * <b>Operation:</b><br/>
	 * T: GPR[rd] &larr; GPR[rs] + GPR[rt]
	 */
	@Override
	public final void execute(final int instruction) {

		mips.instructions.Instruction.RS = (instruction >> 21) & 0x0000001F;
		mips.instructions.Instruction.RT = (instruction >> 16) & 0x0000001F;
		mips.instructions.Instruction.RD = (instruction >> 11) & 0x0000001F;

		final long u32_gpr_rs = Instruction.zeroExtendW(mips.R4300i.GPR[mips.instructions.Instruction.RS]); 
		final long u32_gpr_rt = Instruction.zeroExtendW(mips.R4300i.GPR[mips.instructions.Instruction.RT]);

		// cast 64-bit result back down to 32-bit, ignoring overflow
		mips.R4300i.GPR[mips.instructions.Instruction.RD] = (int)((u32_gpr_rs + u32_gpr_rt) & mips.Constants.MAX_U32_AS_S64);

		mips.R4300i.PC = mips.R4300i.nPC;
		mips.R4300i.nPC = mips.R4300i.PC + 4;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String emit(int instruction) {

		mips.instructions.Instruction.RS = (instruction >> 21) & 0x0000001F;
		mips.instructions.Instruction.RT = (instruction >> 16) & 0x0000001F;
		mips.instructions.Instruction.RD = (instruction >> 11) & 0x0000001F;

		return 	"		u32_gpr_rs = mips.instructions.Instruction.zeroExtendW(mips.CPU.GPR["+mips.instructions.Instruction.RS+"]);\n" +
				"		u32_gpr_rt = mips.instructions.Instruction.zeroExtendW(mips.CPU.GPR["+mips.instructions.Instruction.RT+"]);\n" +
				"		\n" + 
				"		mips.CPU.GPR["+mips.instructions.Instruction.RD+"] = (int)((u32_gpr_rs + u32_gpr_rt) & "+mips.Constants.MAX_U32_AS_S64+"L);\n" + 
				"		\n" + 
				"		mips.CPU.PC = mips.CPU.nPC;\n" + 
				"		mips.CPU.nPC = mips.CPU.PC + 4;\n";
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName(final int instruction) {
		return getName();
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName() {
		return INSTRUCTION_NAME;
	}
}